package com.yisu.expressway.weather;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.location.LocationInfo;
import com.yisu.expressway.location.LocationListener;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.utils.DateUtil;
import com.yisu.expressway.ui.recyclerview.DisableScrollGridLayoutManager;
import com.yisu.expressway.ui.recyclerview.DividerGridItemDecoration;
import com.yisu.expressway.utils.DateUtils;
import com.yisu.expressway.utils.DisplayUtil;
import com.yisu.expressway.utils.ToastUtil;
import com.yisu.expressway.weather.adapter.DailyWeatherAdapter;
import com.yisu.expressway.weather.adapter.LifeSuggestionAdapter;
import com.yisu.expressway.weather.model.DailyWeatherObj;
import com.yisu.expressway.weather.model.LifeSuggestion;
import com.yisu.expressway.weather.model.SuggestionObj;
import com.yisu.expressway.weather.model.WeatherCurrentObj;
import com.yisu.expressway.weather.model.WeatherObj;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

public class WeatherActivity extends BaseActivity {

    @Bind(R.id.tv_current_city)
    protected TextView mTvCity;
    @Bind(R.id.tv_current_weather)
    protected TextView mTvCurrentWeather;
    @Bind(R.id.tv_current_temp)
    protected TextView mTvCurrentTemp;
    @Bind(R.id.tv_current_date)
    protected TextView mTvCurrentDate;
    @Bind(R.id.rv_daily_list)
    protected RecyclerView mRv_dailyList;
    @Bind(R.id.rv_suggest_list)
    protected RecyclerView mRv_suggestionList;
    @Bind(R.id.activity_weather)
    protected LinearLayout mRootView;
    @Bind(R.id.margin_top)
    protected View mFirstMargin;
    @Bind(R.id.margin_second)
    protected View mSecondMargin;

    DailyWeatherAdapter mDailyAdapter;
    LifeSuggestionAdapter mSuggestionAdapter;

    LocationInfo mLocationInfo;
    WeatherObj mWeatherObj;

    private final static String WEATHER_RESULT = "weather_result";
    private final static String CURRENT_CITY = "current_city";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_weather);
        initView(getIntent());
    }

    public static void launch(Context context,WeatherObj weatherObj,String city){
        Intent intent = new Intent(context, WeatherActivity.class);
        intent.putExtra(WEATHER_RESULT,weatherObj);
        intent.putExtra(CURRENT_CITY,city);
        context.startActivity(intent);
    }

    private void initView(Intent intent){
        mDailyAdapter = new DailyWeatherAdapter(this);
        mSuggestionAdapter = new LifeSuggestionAdapter(this);
        mRv_dailyList.setLayoutManager(new DisableScrollGridLayoutManager(this,3));
        mRv_dailyList.setAdapter(mDailyAdapter);

        mRv_suggestionList.setLayoutManager(new DisableScrollGridLayoutManager(this,3));
        mRv_suggestionList.addItemDecoration(new DividerGridItemDecoration(this));
        mRv_suggestionList.setAdapter(mSuggestionAdapter);

        if(intent.getSerializableExtra(WEATHER_RESULT) != null){
            updateView((WeatherObj)intent.getSerializableExtra(WEATHER_RESULT));
            mTvCity.setText(intent.getStringExtra(CURRENT_CITY));
        }else {
            getCurrentLocation();
        }
    }

    @OnClick(R.id.backBtn)
    public void clickBack(){
        finish();
    }

    /**
     * 获取当前位置
     */
    private void getCurrentLocation(){
        showLoading();
        LocationService.getInstance().start(new LocationListener() {
            @Override
            public void onSuccess(LocationInfo info) {

                mLocationInfo = info;
                mTvCity.setText(info.getCity());
                getWeather();
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                ToastUtil.displayShortToastMsg(WeatherActivity.this,errorMessage);
                dismissLoading();
            }
        });
    }

    private void getWeather(){
        Map<String, Object> params = new HashMap();
        params.put("location", mLocationInfo.getLatitude() + ":" + mLocationInfo.getLongitude());

        ApiClientHelper.postApi(ApiSetting.getWeather(), new TypeToken<WeatherObj>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<WeatherObj>>() {
            @Override
            public void onResponse(ApiResult<WeatherObj> result) {

                dismissLoading();

                if (!result.success) {
                    ToastUtil.displayLongToastMsg(WeatherActivity.this, result.getMsg());
                    return;
                }

                WeatherObj weatherObj = result.getResult();
                updateView(weatherObj);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismissLoading();
                ToastUtil.displayShortToastMsg(WeatherActivity.this, volleyError.getMessage());
            }
        }, this);
    }

    private void updateView( WeatherObj weatherObj ){
        if(weatherObj != null){
            ArrayList<DailyWeatherObj> dailyList = weatherObj.daily;
            if(dailyList != null && dailyList.size() > 0){
                DailyWeatherObj todayObj = dailyList.get(0);
                StringBuilder todayDate = new StringBuilder(DateUtils.getMonthAndDay(todayObj.date));
                todayDate.append(" ").append(DateUtils.getWeek(todayObj.date));
                mTvCurrentDate.setText(todayDate.toString());
                mDailyAdapter.setData(dailyList);
            }

            WeatherCurrentObj currentObj = weatherObj.now;
            if(currentObj != null){
                mTvCurrentTemp.setText(currentObj.now.temperature + "\u2103");
                mTvCurrentWeather.setText(currentObj.now.text);
                mRootView.setBackgroundResource(ResUtils.getWeatherBg(currentObj.now.code));
                adjustModuleWidth(mFirstMargin);
                adjustModuleWidth(mSecondMargin);
            }

            ArrayList<SuggestionObj> suggestList = new ArrayList<>();
            WeatherObj.DailySuggestion dailySuggestion = weatherObj.suggestion;

            if(dailySuggestion == null){
                return;
            }

            LifeSuggestion lifeSuggestion = dailySuggestion.suggestion;
            if(lifeSuggestion.dressing != null){
                SuggestionObj obj = lifeSuggestion.dressing;
                obj.iconResId = R.drawable.ic_dress;
                obj.title = "穿衣指数";
                suggestList.add(obj);
            }

            if(lifeSuggestion.car_washing != null){
                SuggestionObj obj = lifeSuggestion.car_washing;
                obj.iconResId = R.drawable.ic_car_washing;
                obj.title = "洗车指数";
                suggestList.add(obj);
            }

            if(lifeSuggestion.sport != null){
                SuggestionObj obj = lifeSuggestion.sport;
                obj.iconResId = R.drawable.ic_sport;
                obj.title = "运动指数";
                suggestList.add(obj);
            }
            if(lifeSuggestion.uv != null){
                SuggestionObj obj = lifeSuggestion.uv;
                obj.iconResId = R.drawable.ic_uv;
                obj.title = "紫外线强度";
                suggestList.add(obj);
            }
            if(lifeSuggestion.flu != null){
                SuggestionObj obj = lifeSuggestion.flu;
                obj.iconResId = R.drawable.ic_flu;
                obj.title = "感冒指数";
                suggestList.add(obj);
            }
            if(lifeSuggestion.travel != null){
                SuggestionObj obj = lifeSuggestion.travel;
                obj.iconResId = R.drawable.ic_travel;
                obj.title = "旅游指数";
                suggestList.add(obj);
            }

            mSuggestionAdapter.setData(suggestList);
        }

    }

    protected void adjustModuleWidth(View view){
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        lp.height = DisplayUtil.dip2px(this,40) - NavigationBarHeight / 2;
        view.setLayoutParams(lp);
    }
}
